import { addAddress, getAddress, updateAddress } from '../../../api/address'
import QQMapWX from '../../../libs/qqmap-wx-jssdk.min'
import Schema from 'async-validator'
Page({
  // 页面的初始数据
  data: {
    name: '', // 收货人
    phone: '', // 手机号码
    provinceName: '', // 省
    provinceCode: '', // 省编码
    cityName: '', // 市
    cityCode: '', // 市编码
    districtName: '', // 区
    districtCode: '', // 区编码
    address: '', // 详细地址
    fullAddress: '', // 完整地址
    isDefault: false //是否设置为默认地址，0 不设置为默认，1 设置为默认
  },
  async validatorAddress(params){
    // 定义验证规则
    const nameRegExp = '^[a-zA-Z\\d\\u4e00-\\u9fa5]+$'
    const phoneReg = '^1(?:3\\d|4[4-9]|5[0-35-9]|6[67]|7[0-8]|8\\d|9\\d)\\d{8}$'
    const rule = {
      name: [
        { required: true, message: '请输入收货人姓名' },
        { pattern: nameRegExp, message: '收货人姓名不合法' }
      ],
      phone: [
        { required: true, message: '请输入收货人手机号' },
        { pattern: phoneReg, message: '收货人手机号不合法' }
      ],
      provinceName: { required: true, message: '请选择收货人所在地区' },
      address: { required: true, message: '请输入详细地址' }
    }
    // 实例化
    const validator = new Schema(rule)
    // 验证
    return new Promise( resolve => {
      validator.validate(params, (errors) => {
        if(errors){
          wx.toast({title: errors[0].message})
          resolve({ valid: false })
        }
        else{
          resolve({ valid: true })
        }
      })
    })
  },
  // 保存收货地址
  async saveAddrssForm() {
    const {provinceName,cityName,districtName,address,isDefault} = this.data
    const params = {
      ...this.data,
      fullAddress: provinceName+cityName+districtName+address,
      isDefault: isDefault? 1 : 0
    }
    const { valid } = await this.validatorAddress(params)
    if(!valid) return
    const res = this.activeId
      ?await updateAddress(params)
      :await addAddress(params)
    if(res.code === 200){
      wx.navigateBack({
        success:()=>{
          wx.toast({title: this.activeId? '更新收货地址成功':'新增收货地址成功' })
        }
      })
    }
  },
  async onLocation(){
    try{
      const { latitude, longitude, name } = await wx.chooseLocation()
      this.qqmapwx.reverseGeocoder({
        location:{
          latitude,
          longitude
        },
        success:(res)=>{
          // 地址 街道/门牌号 详细地址
          const { adcode, province, city, district } = res.result.ad_info
          const { street, street_number } = res.result.address_component
          const { standard_address } = res.result.formatted_addresses
          this.setData({
            provinceName: province,
            provinceCode: adcode.replace(adcode.substring(2,6),"0000"),
            cityName: city,
            cityCode: adcode.replace(adcode.substring(4,6),"00"),
            districtName: district,
            districtCode: district && adcode,
            address: street + street_number + name,
            fullAddress: standard_address + name
          })
        }
      })
    }
    catch(err){
      return false
    }
  },
  // 省市区选择
  onAddressChange(event) {
    const [provinceName,cityName,districtName] = event.detail.value
    const [provinceCode,cityCode,districtCode] = event.detail.code
    this.setData({
      provinceName,
      cityName,
      districtName,
      provinceCode,
      cityCode,
      districtCode
    })
  },
  async showData(id){
    if(!id) return
    wx.setNavigationBarTitle({
      title: '更新收货地址'
    })
    this.activeId = id
    const { data } = await getAddress(id)
    this.setData(data)
  },
  onLoad(options){
    this.showData(options.id)
    this.qqmapwx = new QQMapWX({
      key: "EUPBZ-CGACQ-LZW5M-2FC2K-HDNL5-DMB6O"
    })
  }
})
